//
//  JZHTopicViewController.m
//  极致荟
//
//  Created by mac on 14-4-8.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHTopicViewController.h"
#import "JZHFirstLevelViewController.h"
#import "JZHTopicTemplateListVC.h"
#import "SBPageFlowView.h"
#import "JZHCityListViewController.h"
#import "JZHProductDetailsViewController.h"
#import "MMProgressHUD+HUDShowExtral.h"
#import "JZHReview.h"
#import "JZHBlackCardDetailViewController.h"
#import "BRTBeaconSDK.h"
#import "BRTBeacon.h"
#import "JZHBCViewController.h"
#import "JZHZBRViewController.h"
@interface JZHTopicViewController ()<SBPageFlowViewDelegate,SBPageFlowViewDataSource>{
    NSArray *_imageArray;
    
    NSInteger    _currentPage;
    NSMutableArray *souarr;
    SBPageFlowView  *_flowView;
    UIButton *rightButton;
    
    BRTBeacon *beacon;
    NSMutableArray *beaconarr;
    JZHBCViewController *bc;
}
@property (weak, nonatomic) IBOutlet UIButton *ewm;
@property (weak, nonatomic) IBOutlet UIButton *sqx;
@property (weak, nonatomic) IBOutlet UIImageView *soubimage;

@end

@implementation JZHTopicViewController


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.table.hidden=YES;

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if(rightButton)
    {
        
        NSLog(@"%@",[User defuceUser].citydic);
        NSString *cityname=[[User defuceUser].citydic objectForKey:@"name"];
        if(!cityname)
        {
            [rightButton setTitle:@"上海" forState:UIControlStateNormal];
            [self loadTopViewData:2];

        }else
        {
            [rightButton setTitle:cityname forState:UIControlStateNormal];
            [self loadTopViewData:[[[User defuceUser].citydic objectForKey:@"id"] intValue]];

        }
        
    }
    
    
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [[JZHTabbarViewController shareInstance] showTabBar2];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //
    souarr=[[NSMutableArray alloc]init];
    [self setNavigation];
//    [self.souview.layer setCornerRadius:6];
//    [self.souview.layer setBorderWidth:1];
  //  [self.souview.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    
    //scrollview
    // Do any additional setup after loading the view, typically from a nib.
    _imageArray = [[NSArray alloc] init];
    
    [self.soubimage.layer setCornerRadius:6.0];
    [self.soubimage.layer setMasksToBounds:YES];
    self.navigationItem.titleView=self.souview;
    _currentPage = 0;
    
    if(HEIGHT>500)
    {
         _flowView = [[SBPageFlowView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.frame.size.height-20-44-49)];
    }else
    {
         _flowView = [[SBPageFlowView alloc] initWithFrame:CGRectMake(0, -40, self.view.bounds.size.width, self.view.frame.size.height-20-44-49)];
    }
   
    
    _flowView.delegate = self;
    _flowView.dataSource = self;
    _flowView.minimumPageAlpha = 0.6;
    _flowView.minimumPageScale = 0.76;
    // _flowView.defaultImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"1.jpg"]];
    [self.view addSubview:_flowView];
    
    [_flowView reloadData];
//    [BRTBeaconSDK startRangingOption:RangingOptionOnRanged onCompletion:^(NSArray *beacons, BRTBeaconRegion *region, NSError *error)
//     {
//         [beaconarr removeAllObjects];
//         for(BRTBeacon *bt in beacons)
//         {
//             if(bt.major.intValue==888 )
//             {
//                 if(beacon==nil)
//                 {
//                     beacon=bt;
//                     bc=[[JZHBCViewController alloc] initlu:[NSString stringWithFormat:@"%d",beacon.minor.intValue]];
//                     [self presentViewController:bc animated:YES completion:^{
//                         
//                     }];
//                 }
//                 if(beacon.minor==bt.minor)
//                 {
//                     beacon=bt;
//                     continue;
//                 }
//                 if(beacon.minor!=bt.minor && beacon.rssi<bt.rssi)
//                 {
//                     beacon=bt;
//                     
//                     if(bc)
//                     {
//                        [bc dismissViewControllerAnimated:NO completion:^{
//                            
//                        }];
//                         bc=nil;
//                         NSLog(@"%@",[NSString stringWithFormat:@"%d",beacon.minor.intValue]);
//                         bc=[[JZHBCViewController alloc] initlu:[NSString stringWithFormat:@"%d",beacon.minor.intValue]];
//                         [self presentViewController:bc animated:YES completion:^{
//                         }];
//
//                     }else
//                     {
//                         bc=[[JZHBCViewController alloc] initlu:[NSString stringWithFormat:@"%d",beacon.minor.intValue]];
//                         [self presentViewController:bc animated:YES completion:^{
//                
//                             
//                         }];
//                     }
//                     
//                 }
//             }
//             // NSLog(@"%d  %d %ld",bt.major.intValue ,bt.minor.intValue, bt.rssi);
//             
//             
//         }
//         
//     }];

    //
    if (IOS7_OR_LATER) {
        for (UIView *view in self.view.subviews) {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y+66, view.frame.size.width, view.frame.size.height)];
        }
    }
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---导航----
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//导航条设置
-(void)setNavigation
{
    //设置导航视图title
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    [titleLabel setTextColor:[UIColor blackColor]];
    [titleLabel setTextAlignment:NSTextAlignmentCenter];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.text = @"极致荟";
    self.navigationItem.titleView= titleLabel;
    
    //设置右侧导航按钮
    rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 28, 44)];
    
    [rightButton addTarget:self action:@selector(rightbar:) forControlEvents:UIControlEventTouchUpInside];
    rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    UIImageView *rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"专题-上海箭头.png"]];
    rightImage.frame = CGRectMake(0, 0, 9, 5);
    UIBarButtonItem *rightBarImage = [[UIBarButtonItem alloc] initWithCustomView:rightImage];
    
    NSArray *rightBarArray = [NSArray arrayWithObjects:rightBarImage, rightBarButton,nil];
    self.navigationItem.rightBarButtonItems = rightBarArray;
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notkey:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    ///添加搜索VIEW
    [self.table setFrame:CGRectMake(0, self.souview.frame.origin.y+self.souview.frame.size.height+30, self.table.frame.size.width, 400)];
    [[UIApplication sharedApplication].keyWindow addSubview:self.table];
    self.table.hidden=YES;
}


- (IBAction)quxiaosou:(id)sender
{
    [self.soutext resignFirstResponder];
    self.table.hidden=YES;
    self.ewm.hidden=NO;
    self.sqx.hidden=YES;
}

- (void)notkey:(NSNotification *)key
{

    if(self.soutext.isFirstResponder)
    {
        self.table.hidden=NO;
        self.ewm.hidden=YES;
        self.sqx.hidden=NO;
    }else
    {
        self.table.hidden=YES;
    }
    
    
}
- (IBAction)souer:(UIButton *)sender
{
   [UINavigationController Pus:self ToViewconeroller:[[JZHZBRViewController alloc] init]];
    
}

- (void)rightbar:(UIButton *)but
{
   
    JZHCityListViewController *jzh=[[JZHCityListViewController alloc]init];
    //[jzh setHidesBottomBarWhenPushed:YES];
    [UINavigationController Pus:self ToViewconeroller:jzh];
    
}

#pragma mark-------搜索框代理-------
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField.text.length>0)
    {
      [self souHttpdata:textField.text];
    }
    
  
    
    NSLog(@"%@",textField.text);
    return YES;
    
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if(textField.text.length>0)
    {
        [self souHttpdata:textField.text];
    }
    return YES;
}
#pragma mark-------TableView代理----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    return  souarr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
       return 40;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pengyoucell=@"PengyouCell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:pengyoucell];
    if(!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:pengyoucell];
        [cell.contentView setBackgroundColor:[UIColor blackColor]];
        [cell.textLabel setTextColor:[UIColor whiteColor]];
        [cell.textLabel setFont:[UIFont systemFontOfSize:14.0]];
    }
    JZHCommodity *com=[[JZHCommodity alloc]init];
    com=[souarr objectAtIndex:indexPath.row];
    cell.textLabel.text=com.name;
    NSLog(@"%@",com.name);
       return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    self.table.hidden=YES;
    [self.soutext resignFirstResponder];
    JZHCommodity *com=[[JZHCommodity alloc]init];
    com=[souarr objectAtIndex:indexPath.row];
    if(com.comtype==1)
    {
        
        [UINavigationController Pus:self ToViewconeroller:[[JZHProductDetailsViewController alloc]initCommdodity:com]];
    }else
    {

        [UINavigationController Pus:self ToViewconeroller:
         [[JZHBlackCardDetailViewController alloc]initCommodity:com]];
    }
}

///请求网络数据
- (void)souHttpdata:(NSString *)woke
{
     NSDictionary *postdic=[[NSDictionary alloc]initWithObjectsAndKeys:woke,@"keyword", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/topicContentList") parameters:postdic block:^(id data, HttpReturnCode rerurncode) {
       
        if(rerurncode==0)
        {
            [souarr removeAllObjects];
            NSLog(@"%@",data);
            for(NSDictionary *dicdata in [data objectForKey:@"data"])
            {
                JZHCommodity *cid=[[JZHCommodity alloc]init];
                cid.content=[dicdata objectForKey:@"content"];
                cid.comid=[[dicdata objectForKey:@"id"] intValue];
                cid.favornum=[[dicdata objectForKey:@"favoriteNum"] intValue];
                cid.name=[dicdata objectForKey:@"title"];
                cid.headimage=[dicdata objectForKey:@"image"];
                cid.comtype=[[dicdata objectForKey:@"type"] intValue];
                [souarr addObject:cid];
            }
            [self.table reloadData];
            
        }
    }];
}

- (void)loadTopViewData:(int)cityid
{
    // NSDictionary *postdic=[[NSDictionary alloc]initWithObjectsAndKeys:[[User defuceUser].citydic objectForKey:@"id"],@"areaId", nil];
    NSDictionary *postdic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:cityid],@"cityId", nil];
    if(self.topdic.count==0 && self.topdic)
    {
        [MMProgressHUD showWithStatus:@"数据加载中..."];
    }
    
    
    NSLog(@"%@",[[User defuceUser].citydic objectForKey:@"id"]);
    [HttpRequest httpRequestPost:JZHHTTPURL(@"topic/init") parameters:postdic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==HTTPReturnCodeSuccess)
        {
            
            NSDictionary *datadic=data;
            NSLog(@"%@",datadic);
            self.topdic=[datadic objectForKey:@"data"];
            _imageArray=[self.topdic allValues];
            [_flowView reloadData];
            [MMProgressHUD dismiss];
        }else
        {
            
            UIAlertView *aler= [[UIAlertView alloc]initWithTitle:@"" message:@"数据加载失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"重试", nil ];
            [aler show];
            
        }
        
    }];
}
//返回
-(void)back:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark----UIAlertView代理----
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%d",buttonIndex);
    if(buttonIndex==1)
    {
        
        [self loadTopViewData:[[[User defuceUser].citydic objectForKey:@"id"] intValue]];
        
    }else
    {
        [MMProgressHUD dismiss];
    }
}
#pragma mark - PagedFlowView Datasource
//返回显示View的个数
- (NSInteger)numberOfPagesInFlowView:(SBPageFlowView *)flowView{
    return [self.topdic count];
}

- (CGSize)sizeForPageInFlowView:(SBPageFlowView *)flowView;{
    if(HEIGHT>520)
    {
        return CGSizeMake(230, 400);
    }else
    {
        return CGSizeMake(200, 350);
    }
    
}

//返回给某列使用的View
- (UIView *)flowView:(SBPageFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    UIImageView *imageView=(UIImageView *)[flowView dequeueReusableCell];
    if (!imageView) {
        imageView = [[UIImageView alloc] init];
        imageView.layer.masksToBounds = YES;
    }
    NSLog(@"**%d",[self.topdic allValues].count);
    [ImageCache imageUrl:[[[self.topdic allValues]objectAtIndex:index] objectForKey:@"image"] UiImageview:imageView];
    return imageView;
}

#pragma mark - PagedFlowView
- (void)didReloadData:(UIView *)cell cellForPageAtIndex:(NSInteger)index
{
    UIImageView *imageView = (UIImageView *)cell;
    [ImageCache imageUrl:[[[self.topdic allValues]objectAtIndex:index] objectForKey:@"image"] UiImageview:imageView];
    
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(SBPageFlowView *)flowView {
    NSLog(@"Scrolled to page # %d", pageNumber);
    _currentPage = pageNumber;
}

- (void)didSelectItemAtIndex:(NSInteger)index inFlowView:(SBPageFlowView *)flowView
{
    NSLog(@"didSelectItemAtIndex: %d", index);
    NSString *name=[[[self.topdic allValues]objectAtIndex:index] objectForKey:@"name"] ;
    
    JZHFirstLevelViewController *giftFirstLevelVC = [[JZHFirstLevelViewController alloc] initzid:[[[self.topdic allKeys] objectAtIndex:index] intValue]type:[[[[self.topdic allValues]objectAtIndex:index] objectForKey:@"type"] intValue]name:name];
    [UINavigationController Pus:self ToViewconeroller:giftFirstLevelVC];
    
}


- (IBAction)souquxiao:(id)sender {
   
}
@end
